package com.yy.wga.mp.module.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yy.wga.mp.module.order.service.OrderGoodsService;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.mp.common.interceptor.RequestUserHolder;
import com.yy.wga.mp.common.utils.common.StringUtils;
import com.yy.wga.mp.common.utils.mapping.BeansUtils;
import com.yy.wga.mp.module.admin.request.AdminOrderGoodsPageRequest;
import com.yy.wga.mp.module.admin.response.AdminOrderGoodsDetailResponse;
import com.yy.wga.mp.module.admin.response.AdminOrderGoodsPageResponse;
import com.yy.wga.mp.module.order.entity.pojo.OrderGoodsDO;
import com.yy.wga.mp.module.order.mapper.OrderGoodsMapper;
import com.yy.wga.mp.module.order.request.OrderGoodsPageRequest;
import com.yy.wga.mp.module.order.response.OrderGoodsPageResponse;
import com.yy.wga.mp.module.user.entity.pojo.UserBaseDO;
import com.yy.wga.mp.module.user.service.UserBaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 商品购买订单信息(OrderGoods)表服务实现类
 *
 * @author guochao
 * @since 2024-10-26 10:34:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoodsDO> implements OrderGoodsService {
    private final UserBaseService userBaseService;

    @Override
    public PageBean<AdminOrderGoodsPageResponse> pageData(AdminOrderGoodsPageRequest request) {
        // 查询订单
        Long userId = null;
        if (StringUtils.isNotBlank(request.getPhone())) {
            UserBaseDO userBaseDO = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                    .eq(UserBaseDO::getPhone, request.getPhone()));
            if (userBaseDO != null) {
                userId = userBaseDO.getId();
            }
        }
        LambdaQueryWrapper<OrderGoodsDO> queryWrapper = new LambdaQueryWrapper<OrderGoodsDO>()
                .eq(OrderGoodsDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .eq(userId != null, OrderGoodsDO::getFromUserId, userId)
                .eq(request.getStatus() != null, OrderGoodsDO::getStatus, request.getStatus())
                .eq(StringUtils.isNotBlank(request.getOrderNo()), OrderGoodsDO::getOrderNo, request.getOrderNo())
                .gt(request.getStartPayTime() != null, OrderGoodsDO::getPayTime, request.getStartPayTime())
                .lt(request.getEndPayTime() != null, OrderGoodsDO::getPayTime, request.getEndPayTime())
                .orderByDesc(OrderGoodsDO::getId);
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<OrderGoodsDO> orderGoodsList = baseMapper.selectList(queryWrapper);
        List<AdminOrderGoodsPageResponse> responseList = BeansUtils.mapList(orderGoodsList, AdminOrderGoodsPageResponse.class);

        // 填充信息
        if (!CollectionUtils.isEmpty(responseList)) {
            // 查询用户手机
            Set<Long> userIdSet = responseList.stream()
                    .map(AdminOrderGoodsPageResponse::getFromUserId).collect(Collectors.toSet());
            List<UserBaseDO> userBaseList = userBaseService.listByIds(userIdSet);
            Map<Long, UserBaseDO> userMap = userBaseList.stream()
                    .collect(Collectors.toMap(UserBaseDO::getId, Function.identity()));

            for (AdminOrderGoodsPageResponse response : responseList) {
                UserBaseDO userBaseDO = userMap.get(response.getFromUserId());
                if (userBaseDO != null) {
                    response.setFromUserPhone(userBaseDO.getPhone());
                }
            }
        }

        PageBean<AdminOrderGoodsPageResponse> pageBean = new PageBean<>();
        pageBean.setPageInfo(orderGoodsList);
        pageBean.setList(responseList);
        return pageBean;
    }

    @Override
    public AdminOrderGoodsDetailResponse getDetail(Long id) {
        OrderGoodsDO orderGoods = baseMapper.selectOne(new LambdaQueryWrapper<OrderGoodsDO>()
                .eq(OrderGoodsDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .eq(OrderGoodsDO::getId, id));
        if (orderGoods == null) {
             throw new BusinessException("订单不存在");
        }
        AdminOrderGoodsDetailResponse response = BeansUtils.map(orderGoods, AdminOrderGoodsDetailResponse.class);
        // 查用户
        UserBaseDO userBaseDO = userBaseService.getById(orderGoods.getFromUserId());
        if (userBaseDO != null) {
            response.setFromUserPhone(userBaseDO.getPhone());
        }
        return response;
    }

    @Override
    public List<OrderGoodsPageResponse> list(OrderGoodsPageRequest request) {
        LambdaQueryWrapper<OrderGoodsDO> queryWrapper = new LambdaQueryWrapper<OrderGoodsDO>()
                .eq(OrderGoodsDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .eq(OrderGoodsDO::getFromUserId, RequestUserHolder.getUserCache().getUserId())
                .eq(request.getStatus() != null, OrderGoodsDO::getStatus, request.getStatus())
                .orderByDesc(OrderGoodsDO::getId);
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        List<OrderGoodsDO> orderGoodsList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(orderGoodsList)) {
            return Collections.emptyList();
        }
        return BeansUtils.mapList(orderGoodsList, OrderGoodsPageResponse.class);
    }
}
